import React, { useEffect, useState, useContext, useCallback, useMemo, Fragment } from 'react';
import '@/components/SchemaComponent/SchemaManage/styles.less';
import { Button, Card, Col, Form, Row, Badge, Space } from 'antd';
import { SchemaManageAPI } from '@/components/SchemaComponent/SchemaManage/type';
import { SearchOutlined, ReloadOutlined, FilterOutlined } from '@ant-design/icons';
import { SearchComponent } from '../SearchComponent';
import _ from 'lodash';
import cls from 'classnames';
import { ManageContext } from '../../store';
import { handleFilterPayload } from '../../hooks/useHandleDeptValues';

export const SearchBox: React.FC<SchemaManageAPI.ISearchBox> = ({ onOpenFilter, isShowSeniorBtn, switchOpt, setSwitch, form, onSearchClick }) => {
  const { Search, SearchRenderProps } = useContext(ManageContext);

  const [clearNum, setClearNum] = useState<boolean>(false);

  useEffect(() => {
    setSwitch({}); //初始设为空
    initialSwitch();
  }, [Search?.switchList?.length]);

  useEffect(() => {
    if (Object.keys(Search.searchValues).length > 0) {
      /**切换内置Tab清除搜索条件 */
      // form.setFieldsValue({
      //   ...Search.searchValues,
      //   ...Search.searchDeptUserValues,
      // });
    } else {
      // form.resetFields();
    }
  });

  /*获取初始头部选中的选项*/
  const initialSwitch = () => {
    if (Search?.switchList?.length > 0) {
      for (let i = 0; i <= Search.switchList?.length; i++) {
        let item = Search.switchList[i];
        if (item?.visible) {
          onColClick(item?.key, item?.params);
          return;
        }
      }
    } else {
      Search?.onSwitch('', {}, {});
    }
  };

  /* 筛选搜索需要的值 */
  const screenValues = (values: any) => {
    let newValues: any = {};
    if (values) {
      Object?.keys(values).forEach((item) => {
        if (values?.[item] || values?.[item] >= 0) {
          newValues[item] = values?.[item];
        }
      });
    }

    return newValues;
  };

  /* 点击切换 */
  const onColClick = (key: SchemaManageAPI.ISwitchKey, params?: Record<string, any>) => {
    /**切换内置Tab清除搜索条件 */
    form.resetFields();

    if (key) {
      let searchValues = screenValues(form.getFieldsValue());
      setSwitch({
        key: key,
        params: params,
      });
      Search?.saveFilterValues({});
      Search?.onSwitch(key, searchValues, params); //切换方法
    } else {
      return;
    }
  };

  /* 重置刷新点击事件 */
  const onResetClick = () => {
    form.resetFields();
    if (Search?.onReset) {
      Search.onReset({
        ...switchOpt?.params,
      });
    }
    setClearNum(true); /** 触发number组件清空计数变量 */
  };

  /* 表单改变存储表单值 */
  const onFormValuesChange = useCallback(
    (target: any, allValues: any) => {
      const titleValues: any = {};
      let orgFormList = handleFilterPayload(target, Search.searchList);
      let newAllValues = {
        ...Search.searchDeptUserValues,
        // ...allValues,
        ...orgFormList,
      };
      Object?.keys(newAllValues)?.forEach((i) => {
        // if (!(Array?.isArray(newAllValues[i]) && newAllValues[i]?.length == 0)) {
        if (newAllValues[i]) {
          if (Array?.isArray(newAllValues[i]) && newAllValues[i]?.length == 0) {
            // titleValues[`${i}`] = null
          } else {
            titleValues[`${i}`] = newAllValues[i];
          }
        }
        // }
      });
      Search.saveSearchDeptUserValue(titleValues);
      form?.setFieldsValue(titleValues);
      let searchValue = {
        ...switchOpt?.params,
        ...allValues,
      };
      Search.saveSearchValue({ ...searchValue });
    },
    [Search],
  );

  // 处理高级筛选的个数
  const handleFilterLength = useMemo(() => {
    let delItem: string[] = [];
    let filterkeyList: string[] = Object?.keys(Search?.filterDrawerValues)?.filter((item: string) => item != 'undefined');
    Search?.searchList?.forEach((itemDel: any) => {
      if (itemDel?.componentType == 'DeptAndUser') {
        delItem?.push(itemDel?.formOrgType?.COMP, itemDel?.formOrgType?.DEPT, itemDel?.formOrgType?.POS, itemDel?.formOrgType?.USER);
      }
    });
    filterkeyList = filterkeyList?.filter((itemFil: any) => !delItem?.includes(itemFil));
    return filterkeyList?.length;
  }, [Search?.filterDrawerValues]);

  return (
    <Card className={cls('search-box')} bordered={true} bodyStyle={{ padding: 0 }}>
      {SearchRenderProps?.otherSearchForm ? (
        <>{SearchRenderProps?.component}</>
      ) : (
        <>
          {Search.switchList && Search.switchList?.length > 0 && (
            // <Row className={cls('search-box-switchCompon')} >
            <Space
              className={cls('search-box-switchCompon')}
              // size={[50, 10]}
              size={[30, 10]}
              wrap={true}
            >
              {/* // <div className={cls('search-box-switchCompon')} > */}
              {Search.switchList.map((item: any, index: any) => {
                if (item?.visible) {
                  let target = item?.key === switchOpt?.key;
                  return (
                    <div
                      // md={item?.md ?? 2}
                      // sm={item?.sm ?? 24}
                      style={{ ...item?.colStyle }}
                      className={item?.className ?? (target ? cls('switch-font-target') : cls('switch-font'))}
                      key={item?.key + index}
                      onClick={() => {
                        onColClick(item?.key, item?.params);
                      }}
                    >
                      {item?.title}
                    </div>
                  );
                }
              })}
            </Space>
          )}
          <div className={cls('search-box-form-layout')}>
            <div className={cls('search-box-form')}>
              <Form form={form} layout={'inline'} onValuesChange={onFormValuesChange}>
                <Row style={{ width: '100%' }} gutter={[16, 16]}>
                  {Search?.searchList &&
                    Search?.searchList?.map((item: any, index: any) => {
                      if (
                        item?.componentType == 'DeptAndUser' || //组织机构
                        item?.componentType == 'NumberRange' //数量范围
                      ) {
                        return (
                          <Fragment key={index + 'title'}>
                            {item?.whetherSenior ? (
                              <></>
                            ) : (
                              <SearchComponent opt={{ ...item, searchForm: form, clearNum, setClearNum }} type={item?.componentType} />
                            )}
                          </Fragment>
                        );
                      } else {
                        return (
                          <Fragment key={item?.name + index}>
                            {item?.whetherSenior ? (
                              <></>
                            ) : (
                              <Col md={item?.md ?? 4} sm={item?.sm ?? 24} key={item?.name}>
                                <Form.Item style={{ ...item?.itemStyle }} name={item?.name} initialValue={item?.initialValue}>
                                  {/* {item?.component
                                ? item.component
                                : getItemCom(item?.componentType, item)} */}
                                  <SearchComponent opt={{ ...item, searchForm: form }} type={item?.componentType} />
                                </Form.Item>
                              </Col>
                            )}
                          </Fragment>
                        );
                      }
                    })}
                </Row>
              </Form>
            </div>
            <div className={cls('search-box-btn')}>
              <Space>
                <Button
                  type={'primary'}
                  icon={<SearchOutlined />}
                  onClick={onSearchClick}
                  onMouseOut={(event: any) => {
                    event?.target?.nodeName == 'BUTTON' ? event?.target?.blur() : event.target.parentNode.blur();
                  }}
                  style={{ marginRight: 0 }}
                >
                  查询
                </Button>
                <Button
                  type={'default'}
                  icon={<ReloadOutlined />}
                  onClick={onResetClick}
                  onMouseOut={(event: any) => {
                    event?.target?.nodeName == 'BUTTON' ? event?.target?.blur() : event.target.parentNode.blur();
                  }}
                  style={{ marginRight: 0 }}
                >
                  重置
                </Button>
                {isShowSeniorBtn && (
                  <Badge size="small" count={handleFilterLength}>
                    <Button
                      type={'default'}
                      icon={<FilterOutlined />}
                      id={cls('filter-btn')}
                      onClick={onOpenFilter}
                      onMouseOut={(event: any) => {
                        event?.target?.nodeName == 'BUTTON' ? event?.target?.blur() : event.target.parentNode.blur();
                      }}
                      style={{ marginRight: 0 }}
                    >
                      {/* 高级筛选 */}
                      更多
                    </Button>
                  </Badge>
                )}
              </Space>
            </div>
          </div>
        </>
      )}
    </Card>
  );
};
